import {Msg_Type, MsgEvent, ChatMessage} from "@/models/message";


/**
 * 聊天服务对象
 */
class ChatService {
     webSocket: WebSocket | null;
     onConnected: (status: boolean) => void;
     showTyping: () => void;
     showRecall: () => void;
     showChatMsg: (msg: ChatMessage) => void;

    constructor() {
        console.debug("[ChatService] constructor ....");
        this.webSocket = null;
        // 连接后回调
        this.onConnected = (status) => {
            if (status) {
                console.debug(">>> websocket连接成功...");
            } else {
                console.debug(">>> websocket连接失败...");
            }
        };
        this.showTyping = () => { };
        this.showRecall = () => { };
        this.showChatMsg = (msg: ChatMessage) => {
            console.log(msg);
        };
    }

    /**
     * 断开连接
     * @returns
     */
    disconnect() {
        if (this.webSocket) {
            this.webSocket.close();
        }
        this.webSocket = null
    }

    /**
     * 连接
     * @returns
     */
    connect(token:string, userId:string) {
        if (!token || !userId) {
            console.error("缺少参数 token、userId")
            return;
        }
        this.webSocket =  new WebSocket(`ws://localhost:7777/ws?user=${userId}&token=${token}`);

        this.webSocket.onopen = () => {
            this.onConnected(true);
        }

        this.webSocket.onmessage = (evt) => {
            console.debug("WS接收msg：", evt.data)

            //{"message":{"id":"25482703-6b073bb3af1e","sender":"chid_aafd79ff6b80","receiver":"chid_50037860dc3f","createTime":"2022-12-03 10:27:12","state":0,"toCustomer":false,"topicId":null,"dataType":"TEXT","localId":"0vgcqoi2yk3p","content":"烦烦烦烦烦烦","voice":null,"status":"CREATE","convId":43,"urlRef":false,"type":0,"stale":false,"transferred":false},"msgModel":"MESSAGE","extend":null}
            const chatData = JSON.parse(evt.data);
            const msgModel = chatData.msgModel;
            const msg = chatData.message;
            if (msgModel === 'MESSAGE') {
                this.handleChatMsg(msg,false);
            }
            else if (msgModel === 'NOTICE') {
                this.handleNoticeMsg(msg)
            }
            else if (msgModel === 'ACTION') {
                this.handleActionMsg(msg)
            }
        };

        this.webSocket.onclose = () => {
            // 关闭 websocket
            this.onConnected(false);
            console.debug("连接关闭...")
        };

        this.webSocket.onerror = (evt) => {
            console.debug("WS发送失败,evt：", evt)
            // 关闭 websocket
            // this.onConnected(false);
            console.error("发生异常...")
        };
    }

    /**
     * 发送聊天消息
     * 包括文本消息，图片消息、视频消息、语音消息、文件消息
     */
    sendMessage(content: string, receiver: string, type:Msg_Type, isGroup:boolean) {
        if (!content || !receiver) {
            console.error("缺少参数content、contact")
            return false;
        }

        const isUrlRef =  type!==Msg_Type.TEXT && type!==Msg_Type.VOICE

        let chatData:any = {
            message: {
                isGroup: isGroup,
                receiver: receiver,
                content: content,
                urlRef: isUrlRef,
                type: type, //消息类型：0文本、1图片、2视频、3语音、4文件
                localId: Date.now(),
            }
        }

        //调用发送消息
        this.webSocket.send(JSON.stringify(chatData));

        //显示到UI中
        chatData.message.createTime = new Date()
        this.handleChatMsg(chatData.message,true)
        return true;
    }

    /**
     * 发送已读消息
     */
    sendRead(msg:ChatMessage) {
        if(!msg.sender || !msg.id){
            console.error(`sender=${msg.sender} 或 msgId=${msg.msgId}不能为空`)
            return false;
        }

        let chatData = {
            "event": MsgEvent.CreateEventRead(msg.id, '',msg.isGroup, msg.sender)
        }
        this.webSocket.send(JSON.stringify(chatData));
        return true;
    }

    /**
     * 发送撤回消息
     */
    sendRecall(msgId:string,chatId:string,isGroup:boolean, receiver:string) {
        if (!msgId || !receiver) {
            console.error("缺少参数 msgId、receiver")
            return;
        }

        let chatData = {
            "event": MsgEvent.CreateEventRecall(msgId, '',isGroup, receiver)
        }
        this.webSocket.send(JSON.stringify(chatData));
        return true;
    }

    /**
     * 处理接收的聊天信息
     * @param msg
     * @param isSelf 是否是自己的消息
     */
    handleChatMsg(msg: ChatMessage,isSelf:boolean) {
        msg.isSelf = isSelf
        this.showChatMsg(msg);
    }

    /**
     * 处理接收的通知信息
     * @param msg
     */
    handleNoticeMsg(msg: any) {
        // console.debug("msg = "+JSON.stringify(msg))
        switch (msg.type) {
            default:
                console.debug("TODO ...")
        }
    }

    /**
     * 处理接收的Action信息
     * @param msg
     */
    handleActionMsg(msg: MsgEvent) {
        console.log(">>> 收到事件消息：msg = ",msg)
        /*switch (msg.command) {
            case "READ":
                console.log(`时间 <= ${msg.target} 的消息全部已读`)
                break;
            case "RECALL":
                this.showRecall(msg.target, msg.sender)
                break;
            case "RECALL_ALLOW":
                this.showRecall(msg.target, msg.sender)
                break;
            case "RECALL_FORBID":
                console.warn(`contact=${msg.sender}，消息撤回失败 msgId = ${msg.target}`)
                break;
            case "TYPING":
                this.showTyping()
                break;
            default:
                console.error(`command=${msg.command}: do nothing`)
        }*/
    }

}


export {
    ChatService,
}

